package sifcom.servlet;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sifcom.Entidades.Factory.CantonFactory;

import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.repackaged.org.json.JSONException;

public class CantonServlet extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = -4593372711329900812L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp){
		
		if(req.getParameter("buscar") != null)
		{
		CantonFactory data = new CantonFactory();
		String datos="";
		try {
			System.out.println("Canton id: "+req.getParameter("buscar"));
			datos = data.SearchByProvincia(req.getParameter("buscar"));
			System.out.println("Datos: "+datos);
		} catch (EntityNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		try {
			resp.setContentType("text/html; charset=UTF-8");
			resp.getWriter().write(datos);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		}
		else
		if(req.getParameter("canton") ==null)
		{
		CantonFactory data = new CantonFactory();
		String datos="";
		try {
			datos = data.getData();
		} catch (EntityNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		try {
			resp.setContentType("text/html; charset=UTF-8");
			resp.getWriter().write(datos);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		}
		else
		{
			
			CantonFactory data = new CantonFactory();
			String datos="";
			try {
				datos = data.Search(req.getParameter("canton") != null ? req.getParameter("canton").toString() : "");
			} catch (EntityNotFoundException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

			try {
				resp.setContentType("text/html; charset=UTF-8");
				resp.getWriter().write(datos);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp){
		try {
			new CantonFactory(req.getReader());	

			this.doGet(req, resp);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (EntityNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
		
}
